iT邦幫忙

2022 iThome 鐵人賽

DAY 16
0

You are writing an embedded system for a Take-A-Number machine. It is a very simple model.

It can give out consecutive numbers and report what was the last number given out.

1. Start the machine

Implement the start/0 function. It should spawn a new process that has an initial state of 0 and is ready to receive messages. It should return the process's PID.

2. Report the machine state

Modify the machine so that it can receive {:report_state, sender_pid} messages. It should send its current state (the last given out ticket number) to sender_pid and then wait for more messages.

3. Give out numbers

Modify the machine so that it can receive {:take_a_number, sender_pid} messages. It should increase its state by 1, send the new state to sender_pid, and then wait for more messages.

4. Stop the machine

Modify the machine so that it can receive a :stop message. It should stop waiting for more messages.

5. Ignore unexpected messages

Modify the machine so that when it receives an unexpected message, it ignores it and continues waiting for more messages.


https://exercism.org/tracks/elixir/exercises/take-a-number

defmodule TakeANumber do
  @moduledoc """
  learning PID and process
  """
  @doc """
  practice spawn the process
  """
  @spec start() :: pid()
  def start() do
    spawn(fn -> loop(0) end)
  end
  @doc """
  recursion receive the process
  """
  defp loop(state) do
    receive do
      {:report_state, pid} ->
        send(pid, state)
        loop(state)
      {:take_a_number, pid} ->
        state = state + 1
        send(pid, state)
        loop(state)
      :stop -> nil
      _ -> loop(state)
    end
  end
end

上一篇
十五. If Statement
下一篇
十七. Keyword Lists
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言